package com.magicsoft.share.ui.article;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.magicsoft.share.R;
import com.magicsoft.share.adapter.article.EditArticleAdapter;
import com.magicsoft.share.base.BaseActivity;
import com.magicsoft.share.bean.article.ArticleContent;
import com.magicsoft.share.bean.article.MyArticleDetail;
import com.magicsoft.share.constant.AppDavikActivityMgr;
import com.magicsoft.share.constant.Constant;
import com.magicsoft.share.customview.alertview.AlertView;
import com.magicsoft.share.customview.alertview.OnItemClickListener;
import com.magicsoft.share.presenter.article.AddArticlePresenter;
import com.magicsoft.share.ui.my.AllShareActivity;
import com.magicsoft.share.utils.OssTool;
import com.magicsoft.share.utils.ToastUtils;
import com.magicsoft.share.view.article.IAddArticleView;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

public class AddArticleActivity extends BaseActivity<IAddArticleView, AddArticlePresenter> implements IAddArticleView {


    @BindView(R.id.view_top)
    View viewTop;
    @BindView(R.id.ibtn_left)
    ImageButton ibtnLeft;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ibtn_right)
    ImageButton ibtnRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.recyclerView)
    SwipeMenuRecyclerView mRecyclerView;
    @BindView(R.id.iv_cover)
    ImageView ivCover;
    @BindView(R.id.tv_article_title)
    TextView tvArticleTitle;




    private EditArticleAdapter articleAdapter;

    private List<LocalMedia> selectList;
    private ArrayList<ArticleContent> articleContents;

    private int mClickPosition;
    private AlertView alertView;
    private OssTool ossManager;

    private String coverStr;
    private String coverRiginalStr;
    private String contentStr;
    private Long articleId;
    private String TAG = "AddArticleActivity";
    private SweetAlertDialog dialog;
    private List<String> filePath = new ArrayList<>();


    @Override
    public AddArticlePresenter initPresenter() {
        return new AddArticlePresenter();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_article;
    }

    @Override
    public void initData() {

        articleContents = ((ArrayList<ArticleContent>) getIntent().getSerializableExtra("articleContents"));
        long articleId = getIntent().getLongExtra("articleId", -1);
        if (articleId == -1) {
            this.articleId = null;
            coverStr = articleContents.get(0).getImg();
            coverRiginalStr = articleContents.get(0).getImg();
        } else {
            this.articleId = articleId;
            mPresenter.myArticleDetail(articleId);
        }

        ossManager = OssTool.getInstance().init(this);
    }

    @Override
    public void initView() {
        tvTitle.setText("编辑");
        tvRight.setText("下一步");
        initRV();
        initDialog();
        initImgDialog();
    }

    @Override
    public void requestData() {

    }

    @OnClick({R.id.ibtn_left, R.id.tv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ibtn_left:
                if (alertView != null) {
                    alertView.dismiss();
                    alertView.show();
                } else {
                    initDialog();
                    alertView.show();
                }
                break;
            case R.id.tv_right:
                if (tvArticleTitle.getText().toString().equals("") || tvArticleTitle.getText().toString() == null) {
                    ToastUtils.showToast(this, "请输入标题");
                    return;
                }
                Intent intent = new Intent(this, ArticlePreviewActivity.class);
                intent.putExtra("titleStr", tvArticleTitle.getText().toString());
                contentStr = new Gson().toJson(articleAdapter.getData());
                intent.putExtra("contentStr", contentStr);
                intent.putExtra("coverStr", coverStr);
                intent.putExtra("coverRiginalStr", coverRiginalStr);
                intent.putExtra("articleId", this.articleId);
                Log.e("DOODOD2", articleId + "");
                startActivity(intent);
                break;
        }
    }

    private void initDialog() {
        alertView = new AlertView.Builder().setContext(this).setTitle("是否存为草稿？").setStyle(AlertView.Style.Alert).setCancelText("删除草稿").setOthers(new String[]{"存为草稿"}).setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {

                if (position == -1) {
                    if (articleId == null || articleId == -1) {
                        finish();
                    } else {
                        mPresenter.deleteArticle(articleId);
                    }
                } else {
                    mPresenter.articleEdit(articleId, tvArticleTitle.getText().toString(), coverStr, coverRiginalStr, contentStr, null, null, null, null, 2);
                }
            }
        }).build();
    }

    private void initRV() {

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        articleAdapter = new EditArticleAdapter(R.layout.item_edt_article, new ArrayList<ArticleContent>());
        articleAdapter.setNewData(articleContents);

        articleAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Log.d("lyf", "onItemChildClick: " + position);

                switch (view.getId()) {
                    case R.id.iv_add_img:
                        mClickPosition = position;
                        addPhoto();
                        break;
                    case R.id.iv_add_text:
                        mClickPosition = position;
                        startActivityForResult(new Intent(AddArticleActivity.this, EdtContentActivity.class), Constant.REQUEST_ARTICLE_ADD_CONTENT);
                        break;
                    case R.id.iv_add:
                        mClickPosition = position;
                        Log.d(TAG, "onItemChildClick: " + articleAdapter.getItem(position).getImg() + articleAdapter.getItem(position).getContent());
                        articleAdapter.addShowOrHide(position);
                        break;
                    case R.id.imageView:
                        mClickPosition = position;
                        Intent intent1 = new Intent(AddArticleActivity.this, CropImageActivity.class);
                        intent1.putExtra("imgUrl", articleAdapter.getItem(position).getImg());
                        startActivityForResult(intent1, Constant.REQUEST_ARTICLE_IMG);
                        break;
                    case R.id.tv_content:
                        mClickPosition = position;
                        Intent intent = new Intent(AddArticleActivity.this, EdtContentActivity.class);
                        intent.putExtra("contentStr", articleAdapter.getItem(position).getContent());
                        startActivityForResult(intent, Constant.REQUEST_ARTICLE_CONTENT);
                        break;
                    case R.id.iv_close:
                        mClickPosition = position;
                        if (articleAdapter.getData().size() == 1) {
                            ToastUtils.showToast(AddArticleActivity.this, "至少保留一张图片");
                        } else {
                            articleAdapter.remove(position);
                        }
                        break;
                    default:
                        break;
                }
            }
        });


//        iv_pop = (ImageView) view.findViewById(R.id.iv_pop);
//        iv_cover = (ImageView) view.findViewById(R.id.iv_cover);
//
        Glide.with(this).load(coverRiginalStr).into(ivCover);

        ivCover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AddArticleActivity.this, CoverActivity.class);
                intent.putExtra("coverStr", coverStr);
                startActivityForResult(intent, Constant.REQUEST_ARTICLE_COVER);
            }
        });
//        tv_article_title = (TextView) view.findViewById(R.id.tv_article_title);
        tvArticleTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AddArticleActivity.this, EdtTitleActivity.class);
                intent.putExtra("titleStr", tvArticleTitle.getText().toString());
                startActivityForResult(intent, Constant.REQUEST_ARTICLE_TITLE);
            }
        });
        mRecyclerView.setAdapter(articleAdapter);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);

                    for (int i = 0; i < selectList.size(); i++) {
                        filePath.add(selectList.get(i).getCompressPath());
                        Log.d("pick", "onActivityResult: " + i + selectList.get(i).getCompressPath());
                    }
                    uploadImg();
                    break;
                case Constant.REQUEST_ARTICLE_TITLE:
                    String articleStr = data.getStringExtra("titleStr");

                    tvArticleTitle.setText(articleStr);
                    break;
                case Constant.REQUEST_ARTICLE_CONTENT:
                    String contentStr = data.getStringExtra("contentStr");

                    Log.d("lyf", "onActivityResult: " + contentStr);

                    articleAdapter.getItem(mClickPosition).setContent(contentStr);
                    articleAdapter.notifyItemChanged(mClickPosition);
                    break;
                case Constant.REQUEST_ARTICLE_ADD_CONTENT:
                    String addContentStr = data.getStringExtra("contentStr");

                    ArticleContent articleContent = new ArticleContent();
                    articleContent.setContent(addContentStr);
                    articleAdapter.addData(mClickPosition + 1, articleContent);
                    articleAdapter.setImg(mClickPosition + 1,articleContent);
                    articleAdapter.notifyDataSetChanged();
                    break;
                case Constant.REQUEST_ARTICLE_COVER:
                    Log.d(TAG, "onActivityResult: ");
                    coverRiginalStr = data.getStringExtra("coverRiginalStr");
                    coverStr = data.getStringExtra("coverStr");
                    Glide.with(this).load(coverStr).into(ivCover);
                    break;
                case Constant.REQUEST_ARTICLE_IMG:
                    String imgUrlStr = data.getStringExtra("imgUrlStr");
                    articleAdapter.getItem(mClickPosition).setImg(imgUrlStr);
                    articleAdapter.notifyItemChanged(mClickPosition);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 键盘返回点击事件
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!alertView.isShowing()) {
                alertView.show();
            } else {
                alertView.dismiss();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void addPhoto() {
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(AddArticleActivity.this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()
                .theme(R.style.picture_style)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                .maxSelectNum(20)// 最大图片选择数量 int
                .minSelectNum(1)// 最小选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .isCamera(false)// 是否显示拍照按钮 true or false
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .compress(true)// 是否压缩 true or false
                .isGif(true)// 是否显示gif图片 true or false
                .openClickSound(true)// 是否开启点击声音 true or false
                .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }


    @Override
    public void articleEditSuccess() {
        ToastUtils.showToast(this, "文章存入草稿箱成功");
        AppDavikActivityMgr.getScreenManager().finishActivity(AllShareActivity.class);
        Intent intent = new Intent(this, AllShareActivity.class);
        intent.putExtra("position", 1);
        startActivity(intent);
        finish();
    }

    @Override
    public void myArticleDetailSuccess(MyArticleDetail data) {
        Log.d("lyf", "myArticleDetailSuccess: ");
        articleId = data.getArticle_id();
        coverStr = data.getCover();
        Glide.with(this).load(coverStr).into(ivCover);
        coverRiginalStr = data.getCover_riginal();
        tvArticleTitle.setText(data.getTitle());
        articleAdapter.setNewData(data.getContent());

    }

    @Override
    public void deleteArticleSuccess() {
        finish();
    }


    private void initImgDialog() {
        dialog = new SweetAlertDialog(AddArticleActivity.this, SweetAlertDialog.PROGRESS_TYPE);
        dialog.getProgressHelper().setBarColor(R.color.main);
        dialog.setTitleText("加载图片中...");
        dialog.setCancelable(true);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {

                ossManager.cancel();
            }
        });
    }

    /**
     * 图片上传阿里云OSS
     */
    private void uploadImg() {
        for (int i = 0; i < filePath.size(); i++) {
            ossManager.upload("article", filePath.get(i), new OssTool.uploadListener() {
                @Override
                public void onSuccess(String url) {
                    ArticleContent articleContent = new ArticleContent();
                    articleContent.setImg(url);
                    articleAdapter.addData(mClickPosition + 1, articleContent);
                }

                @Override
                public void onFail() {
                    dialog.dismiss();
                }
            });
        }
        articleAdapter.notifyDataSetChanged();
        filePath.clear();
    }

}
